import axios from 'axios'
import router from '@/router/index'
import errorCode from '@/utils/errorCode'
import {getCookie} from '@/utils/cookieUtils'
import store from '../store'
// 创建axios实例
const service = axios.create({
  baseURL: process.env.WEB_API, // api 的 base_url
  timeout: 20000 // 请求超时时间 10秒
})

// request拦截器
// HTTPrequest拦截
service.interceptors.request.use(config => {
  // NProgress.start() // start progress bar
  // const isToken = (config.headers || {}).isToken === false
  // let token =  store.getters.access_token
  // if (token && !isToken) {
  //   config.headers['Authorization'] = 'Bearer ' + token// token
  // }
  // headers中配置serialize为true开启序列化
  if (config.method === 'post' && config.headers.serialize) {
    config.data['siteId'] = store.state.app.siteId
    config.data = serialize(config.data)
    delete config.data.serialize
  } else {
    if (config.params) {
      config.params['siteId'] = store.state.app.siteId
    } else {
      config.params = {
        siteId: store.state.app.siteId
      }
    }
  }

  return config
}, error => {
  return Promise.reject(error)
})

// response 拦截器
service.interceptors.response.use(
  response => {
    // return response.data
    const res = response.data
    const status = Number(response.status) || 200
    const message = res.msg || errorCode[status] || errorCode['default']
    if (status !== 200 || res.code === 1) {
      Message({
        message: message,
        type: 'error'
      })
      return Promise.reject(new Error(message))
    }

    return res
  },
  error => {
    // 出现网络超时
    // router.push('500')
    return Promise.reject(error)
  }
)

export default service
